﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
using ViewModel.Response;

namespace Management.Middlewares
{
    /// <summary>
    /// 异常处理
    /// </summary>
    public class ExceptionHandlerMiddleware
    {
        private readonly RequestDelegate _next;

        public ExceptionHandlerMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext httpContext)
        {
            try
            {
                return _next(httpContext);
            }
            catch (Exception ex)
            {
                var result = new ResponseModel<object>
                {
                    Status = ResponseStatus.Fail,
                    Message = ex.Message
                };
                return HandleException(httpContext, result);
            }
            finally
            {
                var result = new ResponseModel<object>();
                switch (httpContext.Response.StatusCode)
                {
                    case 401:
                        result.Status = ResponseStatus.Fail;
                        HandleException(httpContext, result);
                        break;
                    case 403:
                        result.Status = ResponseStatus.Fail;
                        HandleException(httpContext, result);
                        break;
                    case 404:
                        result.Status = ResponseStatus.NotFound;
                        HandleException(httpContext, result);
                        break;
                    default:
                        result.Status = ResponseStatus.Fail;
                        break;
                }
            }
        }


        private Task HandleException(HttpContext context, ResponseModel<object> result)
        {
            context.Response.StatusCode = 200;
            context.Response.ContentType = "application/json;charset=utf-8";
            return context.Response.WriteAsync(JsonConvert.SerializeObject(result));
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static partial class RequestMiddlewareExtensions
    {
        public static IApplicationBuilder UseExceptionHandlerMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ExceptionHandlerMiddleware>();
        }
    }
}
